package com.zhangqiancheng.wcdmaconsole;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import Event.MyEvent;
import Event.MyEventListenerInterface;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ProtocalAndUdp.PackAnalysis;
import com.ProtocalAndUdp.PackRezult;
import com.ProtocalAndUdp.ReadWriteFile;
import com.ProtocalAndUdp.SendDatas;
import com.ProtocalAndUdp.UdpClientSocket;
import com.ProtocalAndUdp.Util;
import com.zhangqiancheng.wcdmaconsole.chart.BarChartViewGenerator;
import com.zhangqiancheng.wcdmaconsole.db.DbHelper;

public class DataActivity extends Activity {

	MyEventListenerInterface lis = null;
	PackRezult result;
	String revContent = null;
	String revId;

	ArrayList<Map<String, Object>> data;
	SQLiteDatabase db;
	ListView listview;
	ImageView ivNet;
	ImageView ivRun;
	ImageView ivCom;
	TextView tvTime;
	EditText value;
	Button btStart;
	Button btStop;
	private Vibrator vibrator;
	/**
	 * 检测心跳包是否正常定时器
	 */
	Timer beatTime;
	/**
	 * 每次收到心跳包时间
	 */
	Date getBeatTime;
	/**
	 * 心跳包间隔时间（秒）
	 */
	int beatInternal = 10;
	/**
	 * 点击开始，记录系统开启时间
	 */
	Date startTime;
	/**
	 * 点击开始后的定时器
	 */
	Timer startTimer;
	/**
	 * 判断是否收到回应包定时器
	 */
	Timer receiveTimer;
	/**
	 * 数据包接收时间
	 */
	Date receiveTime;
	/**
	 * 数据包发送时间
	 */
	Date sendTime;
	/**
	 * 上报信息集合（唯一）
	 */
	List<String> receivedList = new ArrayList<String>();
	/**
	 * udp初始化连接
	 */
	Thread updThread;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 要做的事情
			if (msg.what == 1) {// 心跳包
				setWhenBeatStateError();
			} else if (msg.what == 2) {// 上报信息
				if (startTime != null) {
					// 更新系统运行时间
					tvTime.setText(Util.twoDateDistance(startTime, new Date()));
				}
			} else if (msg.what == 3) {// 数据包是否回应
				if (sendTime != null) {
					if (receiveTime == null) {
						if (new Date().getTime() - sendTime.getTime() > 3100) {// 如果发送2秒之后还是没收到数据，则告警
							ivCom.setImageResource(R.drawable.wrong);
							resetComTime();
						}
					} else {
						ivCom.setImageResource(R.drawable.succ);// 收到回应
						resetComTime();// 重新计时
					}
				}
			}
			super.handleMessage(msg);
		}

		/**
		 * 收发数据包回应重新计时
		 */
		private void resetComTime() {

			sendTime = null;
			receiveTime = null;
		}
	};

	private Runnable run = new Runnable() {
		@Override
		public void run() {

			updateUI();
		}
	};

	private void updateUI() {

		if (revId.equals("0002")) {// 开启回应
			deal0002();
		} else if (revId.equals("0005")) {// 关停回应
			deal0005();
		} else if (revId.equals("0309")) {// 设备状态上报(心跳包)
			deal0309();
		} else if (revId.equals("0324")) {// 设备上报信息
			deal0324();
		} else if (revId.equals("0332")) {// 开启定位请求
			deal0332();
		} else if (revId.equals("0333")) {// 定位上报
			deal0333();
		} else if (revId.equals("0335")) {// 停止定位请求
			deal0335();
		}
	}

	/**
	 * 处理开启回应
	 * 
	 * @throws IOException
	 */
	private void deal0002() {

		if (revContent.equals("0")) {
			receiveTime = new Date();
			toast("连接成功！");
			ivRun.setImageResource(R.drawable.succ);
			try {
				ReadWriteFile.writeTxtFile(this, "系统开始工作");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			alert("开启设备失败，请重新点击开始！");
		}
	}

	private void deal0005() {

		receiveTime = new Date();
		if (revContent.equals("0")) {
			toast("设备已关停！");
			ivRun.setImageResource(R.drawable.wrong);
			resetStartTime();
			Log.d("setting", "设备已关停");
			try {
				ReadWriteFile.writeTxtFile(this, "设备已关停");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (revContent.equals("1")) {
			toast("设备关停失败！");
		}
	}

	/**
	 * 处理心跳包
	 */
	private void deal0309() {
		ivNet.setImageResource(R.drawable.succ);
		getBeatTime = new Date();
	}

	/**
	 * 处理设备上报信息
	 */
	private void deal0324() {
		String[] contents = PackAnalysis.pack0324(result);
		Log.i("w", contents[0] + ", " + contents[1]);
		boolean bSame = false;
		String note = null;
		// 接收信息与listveiw中信息比对
		Map<String, Object> item;
		for (int i = 0; i < data.size(); i++) {
			item = (Map<String, Object>) data.get(i);
			if (item.get("imsi").equals(contents[0])
					&& item.get("imei").equals(contents[1])) {
				// 现红，置顶，震动，
				data.remove(i);
				data.add(0, item);// 置顶
				item.put("red", true);
				bSame = true;
				note = item.get("note").toString();
				break;
			}
		}

		// 插入数据库
		dbAdd(contents[0], contents[1], note);
		if (bSame) {
			if (startTime == null)// 开启时间
				startTime = new Date();
			showList();
			vibration();// 震动
		}
		// 显示采集到的号码数量
		boolean isHave = false;
		for (int i = 0; i < receivedList.size(); i++) {
			if (receivedList.get(i).equals(contents[0]+contents[1])) {
				isHave = true;
				break;
			}
		}
		if (!isHave) {
			receivedList.add(contents[0]+contents[1]);
			EditText count = (EditText) findViewById(R.id.etCount);
			count.setText(receivedList.size() + "");
		}
	}

	/**
	 * 插入上报信息
	 * 
	 * @param imsi
	 * @param imei
	 */
	private void dbAdd(String imsi, String imei, String note) {

		ContentValues values = new ContentValues();
		values.put("imsi", imsi);
		values.put("imei", imei);
		values.put("note", note);
		db.insert(DbHelper.WCDMA_TABLE, null, values);
	}

	/**
	 * 开启请求回应
	 */
	private void deal0332() {

		if (revContent.equals("0")) {
			toast("寻呼成功！");
		} else if (revContent.equals("1")) {
			toast("寻呼失败！");
		}
	}

	private void deal0333() {

		String[] contents = revContent.split("#");
		String rssi = contents[2];
		value.setText(rssi);// 显示的强度值
		// 画图
		int value=Integer.parseInt(rssi);
		reDrawPic(value+100);
	}

	/**
	 * 
	 * @param parseInt
	 */
	private void reDrawPic(int rssi) {

		LinearLayout view = (LinearLayout) findViewById(R.id.chartLayout);
		view.removeAllViewsInLayout();
		BarChartViewGenerator.showBarChartView(view, rssi);
	}

	/**
	 * 关闭请求
	 */
	private void deal0335() {

		if (revContent.equals("0")) {
			toast("寻呼关停成功！");
		} else if (revContent.equals("1")) {
			toast("寻呼关停失败！");
		}
	}

	/**
	 * 震动提示
	 */
	private void vibration() {

		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		long[] pattern = { 100, 400, 100, 400 }; // 停止 开启 停止 开启
		vibrator.vibrate(pattern, -1);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_data);
		ivNet = (ImageView) findViewById(R.id.ivNet);
		ivRun = (ImageView) findViewById(R.id.ivRun);
		ivCom = (ImageView) findViewById(R.id.ivCom);
		tvTime = ((TextView) findViewById(R.id.tvDataShowTitle));
		value = (EditText) findViewById(R.id.etNowValue);
		listview = (ListView) findViewById(R.id.listView1);
		listview.addHeaderView(
				LayoutInflater.from(this).inflate(R.layout.listview_header,
						null), null, false);
		listview.setOnCreateContextMenuListener(listviewContextMenuListener);
		data = new ArrayList<Map<String, Object>>();
		btStart = (Button) findViewById(R.id.btStart);
		btStop = (Button) findViewById(R.id.btStop);
		db = DbHelper.getInstance(this, DbHelper.DATABASE_NAME, null,
				DbHelper.DATABASE_VERSION).getWritableDatabase();

		/** 心跳定时器 **/
		beatTime = new Timer();
		TimerTask tast = new TimerTask() {

			@Override
			public void run() {

				sendMessageToHandler(1);
			}
		};
		handler.post(tast);
		beatTime.schedule(tast, 100, 1000);

		/** 记录系统运行时间定时器 *********/
		startTimer = new Timer();
		TimerTask tastStart = new TimerTask() {

			@Override
			public void run() {

				sendMessageToHandler(2);
			}
		};
		handler.post(tastStart);
		startTimer.schedule(tastStart, 100, 1000);

		/** 记录是否收到数据包时间定时器 *********/
		receiveTimer = new Timer();
		TimerTask tastReceive = new TimerTask() {

			@Override
			public void run() {

				sendMessageToHandler(3);
			}
		};
		handler.post(tastReceive);
		receiveTimer.schedule(tastReceive, 100, 1000);

		Thread updThread = new Thread() {
			public void run() {
				try {
					// 初始化udp监听
					UdpClientSocket client = UdpClientSocket.getClient();
					SharedPreferences prefs = getSharedPreferences(SysSettingActivity.SYS_SETTINGS, Context.MODE_PRIVATE);
					String deviceIp= prefs.getString(SysSettingActivity.DEVICE_IP, SysSettingActivity.DEFAULT_DEVICE_IP);
					String devicePort=prefs.getString(SysSettingActivity.DEVICE_PORT, SysSettingActivity.DEFAULT_DEVICE_PORT);
					String receivePort=prefs.getString(SysSettingActivity.RECEIVE_PORT, SysSettingActivity.DEFAULT_RECEIVE_PORT);
					client.setIp(deviceIp);
					client.setServerPort(Integer.parseInt(devicePort));
					client.setReceivePort(Integer.parseInt(receivePort));
					client.receive();
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("udp监听本地失败！");
				}
			}
		};
		updThread.start();
		
		lis = new MyEventListenerInterface() {// 接收设备数据事件
			public void myEventOccurred(MyEvent event) {
				dealReceiveEvent(event);
			}
		};
		try {
			UdpClientSocket.getClient().getRegister().addMyEventListener(lis);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		
		dbSelectAll();
	}

	/**
	 * 接收数据处理
	 * 
	 * @param event
	 */
	private void dealReceiveEvent(MyEvent event) {

		Log.d("event", event.getRezult().getContent());
		result = event.getRezult();
		revId = event.getRezult().getId();
		revContent = event.getRezult().getContent();
		handler.post(run);
	}

	/***** 设置handler信息 ************/
	private void sendMessageToHandler(int index) {

		Message message = new Message();
		message.what = index;
		handler.sendMessage(message);
	}

	/**
	 * 心跳包异常设置
	 */
	private void setWhenBeatStateError() {

		if (getBeatTime != null) {
			long distance = new Date().getTime() - getBeatTime.getTime();
			if (distance / 1000 > (beatInternal * 2 + 200)) {
				// 心跳异常
				ivNet.setImageResource(R.drawable.wrong);
				// Run异常
				ivRun.setImageResource(R.drawable.wrong);
			}
		}
	}

	/**
	 * 重置系统启动时间
	 */
	private void resetStartTime() {

		tvTime.setText("0:0:0");
		startTime = null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.data, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == R.id.action_back)
			onBackPressed();
		return super.onOptionsItemSelected(item);
	}

	public void onStartClick(View view) {

		try {
			SendDatas.send("00", "01", "");// 发送开启请求
			sendTime = new Date();
			Log.d("setting", "发送：0001");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onStopClick(View view) {

		try {
			SendDatas.send("00", "04", "");// 发送停止请求
			sendTime = new Date();
			// 重置系统运行时间
			resetStartTime();
			Log.d("setting", "发送：0004");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void settingsButtonClick(View view) {

		startActivity(new Intent(getApplicationContext(),
				SettingsActivity.class));
	}

	public void inputButtonClick(View view) {

		startActivityForResult(new Intent(getApplicationContext(),
				InputActivity.class), 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1)
			dbSelectAll();
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void sysButtonClick(View view) {

		startActivity(new Intent(getApplicationContext(), SysActivity.class));
	}

	public void sbtShowClick(View view) {

		startActivity(new Intent(getApplicationContext(),
				DatashowActivity.class));
	}

	private OnCreateContextMenuListener listviewContextMenuListener = new OnCreateContextMenuListener() {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {

			menu.setHeaderTitle("操作");// 标题
			menu.add(0, R.id.findCall, 0, "开始寻呼");
			menu.add(0, R.id.endCall, 0, "停止寻呼");
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		ContextMenuInfo info = item.getMenuInfo();
		AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterView.AdapterContextMenuInfo) info;
		// 获取选中行位置
		int position = contextMenuInfo.position;

		Map<String, Object> oneItem = data.get(position - 1);
		if (item.getItemId() == R.id.findCall) {
			// 开始寻呼
			findCall(oneItem.get("imsi").toString());
		} else {
			// 停止寻呼
			endCall(oneItem.get("imsi").toString());
		}

		return super.onContextItemSelected(item);
	}

	@Override
	protected void onDestroy() {

		try {
			UdpClientSocket.getClient().getRegister()
					.removedMyEventListener(lis);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void showList() {

		MyAdapter listAdapter = new MyAdapter(this);
		((ListView) findViewById(R.id.listView1)).setAdapter(listAdapter);
	}

	private void dbSelectAll() {

		Cursor cursor = db.query(DbHelper.WATCH_TABLE, null, null, null, null,
				null, DbHelper.KEY_ID_ASC);
		data.clear();
		try {
			while (cursor.moveToNext()) {
				String imsi = cursor.getString(1);
				String imei = cursor.getString(2);
				String note = cursor.getString(3);
				boolean red = false;
				addItemToData(imsi, imei, note, red);
			}
		} finally {
			cursor.close();
		}
		showList();
	}

	private void addItemToData(String IMSI, String IMEI, String note,
			boolean red) {

		HashMap<String, Object> item = new HashMap<String, Object>();
		item.put("imsi", IMSI);
		item.put("imei", IMEI);
		item.put("note", note);
		item.put("red", red);
		data.add(item);
	}

	private void alert(String message) {

		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.btn_star);
		builder.setMessage(message);
		builder.setTitle("警告");
		android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {

				arg0.dismiss();
			}
		};
		builder.setPositiveButton("确认", listener);
		builder.create().show();
	}

	private void toast(String message) {

		Toast.makeText(this, message, Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * 停止寻呼
	 */
	private void endCall(String imsi) {

		try {
			SendDatas.send("08", "34", imsi + "#");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 开始寻呼
	 */
	private void findCall(String imsi) {

		try {
			SendDatas.send("08", "31", imsi + "#");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新建一个类继承BaseAdapter，实现视图与数据的绑定
	 */
	private class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;// 得到一个LayoutInfalter对象用来导入布局

		/** 构造函数 */
		public MyAdapter(Context context) {

			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {

			return data.size();// 返回数组的长度
		}

		@Override
		public Object getItem(int position) {

			return data.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		/** 书中详细解释该方法 */
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder holder;
			// 观察convertView随ListView滚动情况
			Log.v("MyListViewBase", "getView " + position + " " + convertView);
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.listview, null);
				holder = new ViewHolder();
				/** 得到各个控件的对象 */
				holder.imsi = (TextView) convertView
						.findViewById(R.id.tvItemIMSI);
				holder.imei = (TextView) convertView
						.findViewById(R.id.tvItemIMEI);
				holder.note = (TextView) convertView
						.findViewById(R.id.tvItemNote);
				convertView.setTag(holder);// 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag();// 取出ViewHolder对象
			}
			if ((Boolean) data.get(position).get("red")) {
				convertView.setBackgroundColor(Color.RED);
			}
			/** 设置TextView显示的内容，即我们存放在动态数组中的数据 */
			holder.imsi.setText(data.get(position).get("imsi").toString());
			holder.imei.setText(data.get(position).get("imei").toString());
			holder.note.setText(data.get(position).get("note").toString());
			return convertView;
		}
	}

	/** 存放控件 */
	public final class ViewHolder {

		public TextView imsi;
		public TextView imei;
		public TextView note;
	}

}
